<template>
  <section class="container">
    <div class="l_nav">
      <div class="user-box">
        <div class="user">
          <div class="user-logo">
            <img src="" alt="">
          </div>
          <div class="user-info">
            <p class="u-name">{{userInfo.name}}</p>
            <p class="u-icon"><span class="el-icon-bell"></span><span class="el-icon-service"></span></p>
          </div>
        </div>
        <div class="search">
          <el-input placeholder="请输入内容" v-model="form.search">

            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>
      </div>
      <div class="nav-tab">
        <ul>
          <li>最近联系</li>
          <li>全部联系</li>
          <li>群</li>
        </ul>
      </div>
      <div class="tab-con">
        <ul class="people-list">
          <li class="people-item" v-for="user in users" :key="user.id" @click="handleJoinChartUser(user)">
            <div class="people-logo">
              <img src="" alt="">
            </div>
            <div class="people-info">
              <p class="p-title"><span class="p-name">{{user.name}}</span><span class="p-time">09:12</span></p>
              <p class="last-msg">啊手动阀手动阀手动阀啊手动阀是的</p>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div class="main">
      <p class="chart-user">{{chartUser.name}}</p>
      <div class="msg-container">
        <ul v-if="chartUser.id" class="msg-list">
          <li class="msg-item" v-for="msg in messageArr" :key="msg.sentTime">
            <p class="msg-time">
              <span v-if="msg.type=='send'">{{msg.sentTime | formartDate}}</span>
              <span v-if="msg.type=='get'">{{msg.receivedTime | formartDate}}</span>
            </p>
            <div :class="msg.type=='send'?'msg-right':'msg-left'" class="msg-context">
              <div class="msg-logo">
                <img src="" alt="">
              </div>
              <div class="msg-text">
                <p class="msg-user-name">{{msg.content.extra.name}}</p>
                <p class="msg-content">{{msg.content.content}}</p>
              </div>
            </div>
          </li>
        </ul>
        <div class="join-chart" v-if="!chartUser.id"></div>
        <!--<p>{{messageArr}}</p>-->
      </div>
      <div class="send-message">
        <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 4 }" v-model="content" :readonly="!chartUser.id"
                  placeholder="请输入内容"></el-input>
      </div>
      <el-button type="primary" @click="handleSendMsg" size="small" class="btn-right" :disabled="!chartUser.id||!content">发送消息</el-button>
    </div>

    <el-dialog title="登录" :visible.sync="dialogFormVisible" :width="width">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item prop="name">
          <el-input v-model="form.name" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" v-model="form.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="success" size="large" style="width:100%" @click="onSubmit" :disabled="isLogin">登录</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </section>
</template>

<script>
  import Api from "../api";
  import {mapActions, mapGetters} from 'vuex'
  export default {
    data(){
      return {
        form: {
          name: "",
          password: ""
        },
        rules: {
          name: [
            {required: true, message: "请输入账号", trigger: "blur"},
            {min: 4, max: 12, message: "长度在 4 到 12 个字符", trigger: "blur"}
          ],
          password: [{required: true, message: "请输入密码", trigger: "blur"}],
        },
        dialogFormVisible: true,
        formLabelWidth: '120px',
        userInfo: {},
        instance: '',
        width: "450px",
        content: '',
        messageArr: [],
        isLogin: false,
        users: [],
        chartUser: {}
      }
    },
    filters: {
      formartDate(value){
        console.log(value)
        let d = new Date(value);
        let year = d.getFullYear();
        let month = d.getMonth() + 1;
        let day = d.getDate() < 10 ? '0' + d.getDate() : '' + d.getDate();
        let hour = d.getHours();
        let minutes = d.getMinutes();
        let seconds = d.getSeconds();
        return year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds;
      }
    },
    methods: {
      handleJoinChartUser(user){
        this.chartUser = user;
      },
      getOldMsg(){
        let conversationType = RongIMLib.ConversationType.PRIVATE; //单聊,其他会话选择相应的消息类型即可。
        let targetId = this.chartUser.id.toString(); // 想获取自己和谁的历史消息，targetId 赋值为对方的 Id。
        let timestrap = null; // 默认传 null，若从头开始获取历史消息，请赋值为 0 ,timestrap = 0;
        let count = 20; // 每次获取的历史消息条数，范围 0-20 条，可以多次获取。
        RongIMLib.RongIMClient.getInstance().getHistoryMessages(conversationType, targetId, timestrap, count, {
          onSuccess: function (list, hasMsg) {
            console.log(list)
            // list => Message 数组。
            // hasMsg => 是否还有历史消息可以获取。
          },
          onError: function (error) {
            console.log("GetHistoryMessages,errorcode:" + error);
          }
        });
      },
      onSubmit() {
        this.$refs.form.validate(valid => {
          if (valid) {
            this.isLogin = true;
            Api.login(this.form).then(res => {
              if (!res.code) {
                this.isLogin = false;
                this.dialogFormVisible = false;
                this.userInfo = res.data
                this.getUserList(res.data.id)
                this.connectRongCloud()

              } else {
                this.$message({
                  type: 'info',
                  message: `action: ${ res.message }`
                });
              }
            })
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      handleSendMsg(){
        let $this = this;
        let msg = new RongIMLib.TextMessage({content: this.content, extra: $this.userInfo});
        let conversationtype = RongIMLib.ConversationType.PRIVATE; // 单聊,其他会话选择相应的消息类型即可。
        let targetId = this.chartUser.id.toString(); // 目标 Id
        console.log(targetId)
        this.instance.sendMessage(conversationtype, targetId, msg, {
            onSuccess: function (message) {
              $this.content = ''
              console.log(message)
              $this.messageArr.push({
                sentTime: message.sentTime,
                content: message.content,
                receivedTime: message.receivedTime,
                type: "send"
              })

              //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
              console.log("Send successfully");
            },
            onError: function (errorCode, message) {
              var info = '';
              switch (errorCode) {
                case RongIMLib.ErrorCode.TIMEOUT:
                  info = '超时';
                  break;
                case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                  info = '未知错误';
                  break;
                case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                  info = '在黑名单中，无法向对方发送消息';
                  break;
                case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                  info = '不在讨论组中';
                  break;
                case RongIMLib.ErrorCode.NOT_IN_GROUP:
                  info = '不在群组中';
                  break;
                case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                  info = '不在聊天室中';
                  break;
                default :
                  info = x;
                  break;
              }
              console.log('发送失败:' + info);
            }
          }
        );
      },
      connectRongCloud(){
        let $this = this;
        let config = {};
        RongIMLib.RongIMClient.init(this.userInfo.appkey, null, config);
        //消息发送链接
        this.instance = RongIMClient.getInstance();
        // 设置连接监听状态 （ status 标识当前连接状态 ）
        // 连接状态监听器
        RongIMClient.setConnectionStatusListener({
          onChanged: function (status) {
            switch (status) {
              case RongIMLib.ConnectionStatus.CONNECTED:
                console.log('链接成功');
                break;
              case RongIMLib.ConnectionStatus.CONNECTING:
                console.log('正在链接');
                break;
              case RongIMLib.ConnectionStatus.DISCONNECTED:
                console.log('断开连接');
                break;
              case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                console.log('其他设备登录');
                break;
              case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
                console.log('域名不正确');
                break;
              case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                console.log('网络不可用');
                break;
            }
          }
        });
        // 消息监听器
        RongIMClient.setOnReceiveMessageListener({
          // 接收到的消息
          onReceived: function (message) {
            console.log(message)
            // 判断消息类型
            switch (message.messageType) {
              case RongIMClient.MessageType.TextMessage:
                $this.messageArr.push({
                  sentTime: message.sentTime,
                  content: message.content,
                  receivedTime: message.receivedTime,
                  type: "get"
                })

                // message.content.content => 消息内容
                break;
              case RongIMClient.MessageType.VoiceMessage:
                // 对声音进行预加载
                // message.content.content 格式为 AMR 格式的 base64 码
                break;
              case RongIMClient.MessageType.ImageMessage:
                // message.content.content => 图片缩略图 base64。
                // message.content.imageUri => 原图 URL。
                break;
              case RongIMClient.MessageType.DiscussionNotificationMessage:
                // message.content.extension => 讨论组中的人员。
                break;
              case RongIMClient.MessageType.LocationMessage:
                // message.content.latiude => 纬度。
                // message.content.longitude => 经度。
                // message.content.content => 位置图片 base64。
                break;
              case RongIMClient.MessageType.RichContentMessage:
                // message.content.content => 文本消息内容。
                // message.content.imageUri => 图片 base64。
                // message.content.url => 原图 URL。
                break;
              case RongIMClient.MessageType.InformationNotificationMessage:
                // do something...
                break;
              case RongIMClient.MessageType.ContactNotificationMessage:
                // do something...
                break;
              case RongIMClient.MessageType.ProfileNotificationMessage:
                // do something...
                break;
              case RongIMClient.MessageType.CommandNotificationMessage:
                // do something...
                break;
              case RongIMClient.MessageType.CommandMessage:
                // do something...
                break;
              case RongIMClient.MessageType.UnknownMessage:
                // do something...
                break;
              default:
              // do something...
            }
          }
        });
        //连接服务器
        RongIMClient.connect(this.userInfo.token, {
          onSuccess: function (userId) {
            console.log("Connect successfully." + userId);
          },
          onTokenIncorrect: function () {
            console.log('token无效');
          },
          onError: function (errorCode) {
            var info = '';
            switch (errorCode) {
              case RongIMLib.ErrorCode.TIMEOUT:
                info = '超时';
                break;
              case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                info = '未知错误';
                break;
              case RongIMLib.ErrorCode.UNACCEPTABLE_PaROTOCOL_VERSION:
                info = '不可接受的协议版本';
                break;
              case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
                info = 'appkey不正确';
                break;
              case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
                info = '服务器不可用';
                break;
            }
            console.log(errorCode);
          }
        });
        //重新连接
        let callback = {
          onSuccess: function (userId) {
            console.log("Reconnect successfully." + userId);
          },
          onTokenIncorrect: function () {
            console.log('token无效');
          },
          onError: function (errorCode) {
            console.log(errorcode);
          }
        };
        let reloadConfig = {
          // 默认 false, true 启用自动重连，启用则为必选参数
          auto: true,
          // 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒，可选
          url: 'cdn.ronghub.com/RongIMLib-2.2.6.min.js',
          // 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选
          rate: [100, 1000, 3000, 6000, 10000]
        };
        RongIMClient.reconnect(callback, reloadConfig);


      },
      getUserList(id){
        Api.getUser(id).then(res => {
          this.users = res.data;
          console.log(res)
        })
      }
    },
    mounted(){
//      this.getUserList()
    }
  }
</script>

<style lang="scss" scoped>
  .container {
    position: absolute;
    width: 1200px;
    height: 768px;
    left: 50%;
    top: 50%;
    margin-left: -600px;
    margin-top: -384px;
    overflow: hidden;
    .l_nav {
      width: 274px;
      height: 100%;
      background: #666;
      border-radius: 6px 0 0 6px;
      overflow: hidden;
      position: relative;
      float: left;
      .user-box {
        height: 127px;
        .user {
          overflow: hidden;
          .user-logo {
            width: 57px;
            height: 57px;
            border-radius: 57px;
            overflow: hidden;
            float: left;
            background-color: red;
            margin: 14px 0 0 22px;
          }
          .user-info {
            float: left;
            margin-left: 18px;
            margin-top: 14px;
            width: 152px;
            .u-name {
              margin: 0;
              color: #fff;
              font-size: 16px;
              font-weight: 700;
              height: 21px;
              line-height: 21px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
            .u-icon {
              margin-top: 13px;
              color: #fff;
              span {
                margin-right: 0.5em;
              }

            }
          }
        }
        .search {
          width: 228px;
          height: 26px;
          border-radius: 26px;
          margin: 15px auto;
        }
      }
      .nav-tab {
        height: 40px;
        ul {
          overflow: hidden;
          list-style: none;
          padding: 0;
          li {
            width: 33.33%;
            text-align: center;
            line-height: 39px;
            float: left;
            cursor: pointer;
            background: #333;
            color: #747474;
            font-size: 14px;
          }
        }
      }
      .tab-con {
        width: 274px;
        height: 602px;
        background: #666;
        overflow: hidden;
        position: relative;
        .people-list {
          height: 100%;
          overflow-y: auto;
          .people-item {
            height: 68px;
            box-sizing: border-box;
            padding: 14px 0 14px 24px;
            position: relative;
            .people-logo {
              width: 41px;
              height: 41px;
              float: left;
              background-color: yellow;
              border-radius: 41px;
              img {
                width: 100%;
                height: 100%;
              }
            }
            .people-info {
              color: #fff;
              float: left;
              width: 165px;
              line-height: 20px;
              font-size: 14px;
              margin-left: 0.5em;
              .p-title {
                overflow: hidden;
                .p-name {
                  float: left;
                  width: 100px;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                }
                .p-time {
                  float: right;
                }
              }
              .last-msg {
                white-space: nowrap;
                text-overflow: ellipsis;
                overflow: hidden;

              }
            }
            &:hover {
              cursor: pointer;
              background-color: rgba(0, 0, 0, 0.3);
              &:before {
                content: "";
                position: absolute;
                width: 6px;
                height: 100%;
                left: 0;
                top: 0;
                background-color: orange;
              }
            }
          }
        }
      }
    }
    .main {
      background: #fafafa;
      position: relative;
      padding: 47px 0 165px;
      border-left: 1px solid #eee;
      height: 100%;
      box-sizing: border-box;
      overflow: hidden;
      border-right: 1px solid #ccc;
      border-top: 1px solid #ccc;
      border-radius: 0 6px 6px 0;
      .chart-user {
        position: absolute;
        left: 10px;
        top: 10px;
      }
      .msg-container {
        box-sizing: border-box;
        padding: 0 20px;
        height: 585px;
        background-color: #f0f0f0f0;
        overflow: hidden;
        .msg-list {
          height: 100%;
          overflow: auto;
          .msg-item {
            overflow: hidden;
            .msg-time {
              text-align: center;
              span {
                display: inline-block;
                padding: 5px;
                background-color: #fff;
              }
            }
            .msg-context {
              width: 80%;
              overflow: hidden;
              padding: 20px 12px;
              &.msg-right {
                float: right;
                .msg-logo {
                  float: right;
                }
                .msg-text {
                  margin-right: 58px;
                }
              }
              &.msg-left {
                float: left;
                .msg-logo {
                  float: left;
                  .msg-text {
                    margin-left: 50px;
                  }
                }
                .msg-text {
                  margin-left: 58px;
                  text-align: left;
                  .msg-user-name {

                  }
                  .msg-content {

                  }
                }
              }
              .msg-logo {
                width: 42px;
                height: 42px;
                border-radius: 42px;
                overflow: hidden;
                background-color: yellow;
                img {
                  width: 100%;
                  height: 100%;
                }
              }
              .msg-text {
                text-align: right;
                .msg-user-name {

                }
                .msg-content {

                }
              }
            }
          }
        }
        .join-chart {
          width: 108px;
          height: 108px;
          background-image: url("~assets/chart.png");
          margin: 190px auto;
        }
      }
    }
  }

</style>
